import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { OrganizationService } from 'src/app/services/organization.service';
import { DepartmentService } from 'src/app/services/department.service';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
@Component({
  selector: 'zepride-department-modal',
  templateUrl: './department-modal.component.html',
  styleUrls: ['./department-modal.component.less']
})
export class DepartmentModalComponent implements OnInit {
  @Input() organizationId = '';
  @Input() notequId = '';
  @Input() presentId = '';
  @Input() treeList;
  departmentlistOfData: []; //部门列表
  params = {
    notequId: '',
    name: '',
    status: '',
    pageIndex: 1,
    countOfPage: 10
  }
  constructor(
    private organizationService: OrganizationService,
    private departmentService: DepartmentService,
    private msg: NzMessageService,
    private modalRef: NzModalRef<DepartmentModalComponent>,
    private route: Router,
  ) { }

  ngOnInit(): void {
    this.queryDepartmentsList();
  }
  async queryDepartmentsList() {
    try {
      //去掉自己部门
      this.params.notequId = this.notequId;
      const data = await this.departmentService.queryDepartmentsList(this.params);
      const list = data.list.map(item => {
        return {
          ...item,
          checked: false
        };
      });
      this.departmentlistOfData = list;

    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  clickskip(url: string) {
    this.route.navigate([url], { queryParams: { Id: 0, organizationId: this.organizationId, parentId: this.presentId } });
    this.cancel();
  }

  cancel() {
    this.modalRef.close();
  }

  confirm() {
    this.modalRef.close(true);
  }

  async updepartment() {
    const params = [];
    //查找选中值对应的Id
    this.treeList.nodes.forEach((t: any) => {
      this.departmentlistOfData.forEach((p: any) => {
        if (t.objectId == p.id && p.checked == true) {
          params.push({ id: t.id, parentId: this.presentId });
        }
      })
    });
    if (params.length == 0) {
      this.msg.error('请选择部门');
      return;
    }
    try {
      await this.organizationService.updateorganizationTree(params);
      this.msg.success('添加部门成功');
      this.confirm();
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
}
